import axios from "@/request";
import OSS from "ali-oss";
import { nanoid } from "nanoid";
import isEmpty from "@/utils/isEmpty";

let client;

axios
    .get("/getOssToken", {
        params: {
            username: "random",
        },
    })
    .then((res) => {
        if (isEmpty(res)) {
            return;
        }
        client = new OSS({
            region: "oss-cn-beijing",
            accessKeyId: res.data.data.accessKeyId,
            accessKeySecret: res.data.data.accessKeySecret,
            stsToken: res.data.data.securityToken,
            refreshSTSToken: async () => {
                const refreshInfo = await axios
                    .get("/getOssToken", {
                        params: {
                            username: "random",
                        },
                    })
                    .catch((e) => {});
                return {
                    accessKeyId: refreshInfo.data.data.accessKeyId,
                    accessKeySecret: refreshInfo.data.data.accessKeySecret,
                    stsToken: refreshInfo.data.data.securityToken,
                };
            },
            refreshSTSTokenInterval: 3600000,
            bucket: "hbushop",
        });
    })
    .catch((e) => {});

const ossUpload = function (location, file) {
    return new Promise((resolve, reject) => {
        let suffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);
        let fileName = "/" + location + "/" + nanoid() + suffix;
        client.multipartUpload(fileName, file).then((res) => {
            let url = res.res.requestUrls[0];
            let result = url.indexOf("?") == -1 ? url : url.substring(0, url.indexOf("?"));
            resolve(result);
        });
    });
};

export default ossUpload;
